package lsl.leetCode.year2023.test0207;

/**
 * description:557.反转字符串中的单词 III
 *
 * @author: liushengli
 * data: 2023/2/7
 */
public class test557 {
    public static void main(String[] args) {
        System.out.println(reverseWords1("Let's take LeetCode contes"));
        //System.out.println(reverseWords1("hehhhhhhe"));
    }

    public static String reverseWords1(String s) {
        StringBuffer sb = new StringBuffer();
        int i = 0;
        while (i < s.length()) {
            int start = i;
            while (i < s.length() && s.charAt(i) != ' ') {
                i++;
            }
            for (int j = start; j < i; j++) {
                sb.append(s.charAt(start + i - j - 1));
            }
            while (i < s.length() && s.charAt(i) == ' ') {
                i++;
                sb.append(' ');
            }
        }
        return String.valueOf(sb);
    }


    public static String reverseWords(String s) {
        char[] arr = new char[s.length()];
        int n = s.length();
        int count = 0;
        int front = 0;
        int back = 0;
        for (int i = 0; i < n; i++) {
            if (32 == s.charAt(i)) {
                count = i;
                back = count - 1;
                arr[count] = s.charAt(i);
            }
            if (count != 0) {
                if (i == n - 1) {
                    back = n - 1;
                    front = count + 1;
                }
                while (front <= back) {
                    arr[front] = s.charAt(back);
                    arr[back] = s.charAt(front);
                    front++;
                    back--;
                }
                front = count + 1;
            }
            if (i == n - 1 && count == 0) {
                back = n - 1;
                while (front <= back) {
                    arr[front] = s.charAt(back);
                    arr[back] = s.charAt(front);
                    front++;
                    back--;
                }
            }
        }
        return String.valueOf(arr);
    }
}
